/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.explorer.ftypes;

import org.json.JSONObject;
import org.webos.java.base.Dialog;
import org.webos.java.base.DialogType;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.NetworkManager;
import org.webos.java.base.fs.FileDescriptor;
import org.webos.java.base.fs.FileException;
import org.webos.java.base.fs.FileManager;
import org.webos.java.explorer.Explorer;
import org.webos.java.root.Log;
/**
 *
 * @author Kostya
 */

@DialogType(jsClass="explorer.FolderEditor")
public class FolderEditor extends Dialog{

    private FileDescriptor descriptor = null;
    private Explorer explorer = null;

    public FolderEditor(Explorer aExplorer, FileDescriptor aDescriptor) {
        super(aExplorer);
        descriptor = aDescriptor;
        explorer = aExplorer;
        getData().fixString("name", aDescriptor.getName());

    }

    @RemoteMessage
    public void cancelClick(JSONObject aObject){
        closeDialog(aObject);
    }

    @RemoteMessage
    public JSONObject okClick(JSONObject aObject){
        try {
            descriptor.setName(aObject.optString("name", ""));
            FileManager.checkFileDescriptorName(descriptor);
            boolean newFile = descriptor.getId()==null;
            descriptor.getProvider().createFolder(descriptor);
            closeDialog(aObject);
            explorer.fileUpdated(descriptor, newFile);
            return null;
        } catch (Throwable t) {
            if(t instanceof FileException){
                return NetworkManager.getErrorObject(102, t.getMessage());
            }
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
            return NetworkManager.getErrorObject(102, "Can't save folder");
        }
    }
}
